<template>
    <div id="contracts">
       <!-- 搜索栏    getContractsList   fetchUsers  -->
       <el-card id="search">
            <el-row>
                <el-col :span="20">
                    <el-input v-model="searchModel.contractName" placeholder="合同名称"  clearable style="width: 200px;" class="filter-item"></el-input> <!-- style="width: 200px;" class="filter-item"   换行否 -->
                    <el-input v-model="searchModel.userId" placeholder="上传人"  clearable style="width: 200px;" class="filter-item"></el-input>
                    <el-button @click="fetchUsers()" type="primary" round   icon="el-icon-search">查询</el-button>
                </el-col>
                <el-col :span="3"> <!-- span  3  左右位置 -->
                <el-button @click="openEditUI(null)" type="primary" icon="el-icon-plus" circle></el-button>
                </el-col>
            </el-row>
        </el-card>
         <!-- 结果列表 -->
        <el-card>
            <el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>

            <el-table-column  label="序号">
            <template v-slot="scope">
                {{ (searchModel.pageNo-1)*searchModel.pageSize + scope.$index + 1 }}
            </template>
            </el-table-column>
            <el-table-column prop="id" label="合同ID" ></el-table-column>
            <el-table-column prop="contractName" label="合同名称" ></el-table-column>
            <el-table-column prop="contractContent" label="合同内容" >
                <template slot-scope="scope">
                    <!-- 假设 contractContent 存储的是 URL -->
                    <a :href="scope.row.contractContent" target="_blank">
                    {{ scope.row.contractContent }} <!-- 显示链接文本，这里直接使用 contractContent -->
                    </a>
                </template>
            </el-table-column>
            <el-table-column prop="startDate" label="开始日期" ></el-table-column>
            <el-table-column prop="endDate" label="结束日期" ></el-table-column>
            <el-table-column prop="contractTypeId" label="合同分类ID" ></el-table-column>
            <el-table-column prop="status" label="合同状态" ></el-table-column>
            <el-table-column prop="userId" label="用户ID" ></el-table-column>
            <el-table-column label="操作" >
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="openEditUI(scope.row.id)">编辑</el-button>
                    <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
            </el-table>
        </el-card>

       


        <!--分页组件 -->
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchModel.pageNo"
        :page-sizes="[5,10,20,50]"
        :page-size="searchModel.pageSize"
        layout="total,sizes, prev, pager, next, jumper"
        :total="total">
        </el-pagination>
        <!-- 新增标签弹层 -->
        <el-dialog title="新增合同" :visible.sync="dialogFormVisible">

                <el-form ref="dataAddForm" :model="formData"  :rules="rules" label-position="right" :label-width="formLabelWidth">

                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="合同名称" prop="contractName" :labelWidth="formLabelWidth">
                                <el-input v-model="formData.contractName"  autocomplete="off"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="开始日期"  prop="startDate" :labelWidth="formLabelWidth">
                                <el-input v-model="formData.startDate"  type="date"  ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="结束日期"  prop="endDate" :labelWidth="formLabelWidth">
                                <el-input v-model="formData.endDate"  type="date" ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="合同分类ID" prop="contractTypeId" :labelWidth="formLabelWidth">
                                <el-input v-model="formData.contractTypeId"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item label="合同状态" prop="status" :labelWidth="formLabelWidth">
                                <el-select v-model="formData.status" placeholder="请选择合同状态">
                                    <el-option
                                        v-for="item in statusOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <!--开窗查询后端数据 -->
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="上传人" prop="userId" :labelWidth="formLabelWidth">
                                <el-select v-model="formData.userId" placeholder="请选择上传人" >
                                <el-option
                                    v-for="user in userOptions"
                                    :key="user.id"
                                    :label="user.userName"
                                    :value="user.id">
                                </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <!--开窗查询后端数据 -->

                  <el-form-item label="合同文件" prop="contractFile">
                    <el-upload
                        class="upload-demo"
                        ref="upload" 
                        action="/file/upload"    
                        :on-success="handleUploadSuccess"
                        :before-upload="beforeUpload"
                        :file-list="fileList"
                        :auto-upload="true">
                        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传合同文件，且不超过500kb</div>
                    </el-upload>
                  </el-form-item>
                    
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="cancel()">取消</el-button>
                    <el-button type="primary" @click="saveUser()">确定</el-button>
                </div>
        </el-dialog>
    </div>
</template>
<script>

import contractsManageAPI from '@/api/contractsManage'
export  default{
    data() {
            return {
                fileList: [], // 用于保存上传的文件列表
                formLabelWidth: "130px",
                statusOptions: [ // 合同状态选项
                { value: '待审批', label: '待审批' },
                { value: '已审批', label: '已审批' },
                { value: '已过期', label: '已过期' },
                ],
                dialogFormVisible: false,//添加表单是否可见
                dialogFormVisible4Edit:false,//编辑表单是否可见
                formData: {  userId: null, // 初始化为null或某个默认值
                      },//表单数据
                userOptions: [], // 用户选项列表   
                total: 0,
                searchModel:{
                    pageNo: 1,
                    pageSize: 10
                },
              
                dataList: [],  //当前页要展示的列表数据
                 rules: {//校验规则
                    contractName: [{ required: true, message: '请输入合同名称', trigger: 'blur' },
                            {
                            min: 2,
                            max: 20,
                            message: "长度在2-20个字符",
                            trigger: 'blur'
                            },
                ]
                } 
            }

        },
        methods:{
            beforeUpload(file) {
                const isJPG = file.type === 'application/pdf'; // 假设只接受PDF文件
                const isLt2M = file.size / 1024 / 1024 < 10; // 假设文件大小不超过500kb

                if (!isJPG) {
                    this.$message.error('上传合同文件只能是PDF格式!');
                    return false;
                }
                if (!isLt2M) {
                    this.$message.error('上传合同文件大小不能超过10M!');
                    return false;
                }
                return true;
           },
           handleUploadSuccess(response, file, fileList) {
            console.log(response);
            if (response.data && response.data.url) {
                // 假设您想要将URL存储在某个列表中以便在表格中显示
                this.fileList.push({ fileName: file.name, url: response.data.url });
                // 如果您还需要将这个URL与合同数据关联，您可以在这里更新formData或其他数据结构
                // 例如：this.formData.contractFileUrl = response.data.url; 但请注意，这取决于您的具体需求
                this.$message.success('合同文件上传成功');
                } else {
                    this.$message.error('上传失败，未获取到文件URL');
                }
            },
         
           //添加    -- this.$refs.dataAddForm.validate((valid)=>{ ---数据验证
           saveUser() {
                //触发表单验证
                this.$refs.dataAddForm.validate((valid)=>{ 
                    if(valid){
                        // 提交请求给后台
                        contractsManageAPI.savecontracts(this.formData).then(response =>{
                        // 成功提示
                         this.$message.success(response.msg);
                        //修改成功关闭窗口   false
                        this.dialogFormVisible = false;
                        // 刷新表格
                        this.getContractsList();
                        });
                    }else{
                        console.log("error submit!!");
                        return false;
                    }
                
                });
            },
            // 删除
            handleDelete(row) {
                
                this.$confirm("次操作永久删除，是否继续？", "提示", {   //confirm  防手抖
                    type: "info"
                }).then((response) => {
                    contractsManageAPI.delletecontracts(row.id).then(response =>{
                        this.$message.success(response.msg);
                    }).finally(() => {
                        //2.重新加载数据
                        this.getContractsList();
                    });
                }).catch(() => {
                    this.$message.info("取消操作");
                });
            },
                
            
           //分页
           handleSizeChange(pageSize){
            this.searchModel.pageSize=pageSize
            this.getContractsList();
           },
           handleCurrentChange(pageNo){
            this.searchModel.pageNo=pageNo
            this.getContractsList();
           },
          
            //弹出添加窗口
            openEditUI(id) {
                if (id == null) {
                       this.openAddUI();
                   } else {
                      this.openEditUIById(id);
                   }
            },
            openAddUI() {
                this.title = '新增合同';
                this.dialogFormVisible = true;
                this.clearForm(); // 假设clearForm是用来重置表单的方法
            },
            // 弹出编辑窗口
            openEditUIById(id) {
                this.title = '修改合同';
                contractsManageAPI.getcontractsById(id).then(response => {
                    if (response.msg === 'success' && response.data != null) {
                        this.formData = response.data;
                        this.dialogFormVisible = true;
                    } else {
                        this.$message.error("数据同步失败,自动刷新");
                    }
                }).catch(error => {
                    this.$message.error("加载数据失败：" + error.message);
                });
            },

             //取消
             cancel() {
                this.dialogFormVisible = false;
                this.dialogFormVisible4Edit = false;
                this.$message.success("操作取消！");
            },
            //重置表单
            clearForm() {
                this.formData = { 
                    fileList: []
                };
                this.$refs.dataAddForm.clearValidate();   
            },
            //查询所有  条件查询
            getContractsList(){
            contractsManageAPI.getContractsList(this.searchModel).then(response=>{ 
             this.dataList=response.data.rows;   //表单数据
             this.total=response.data.total;    //页数
            });
           },
            // 加载用户列表    <!--开窗查询后端数据 -->
            fetchUsers() {
            contractsManageAPI.fetchUsers() // 假设这是获取用户列表的API方法
                    .then(response => {
                        if (response.data && Array.isArray(response.data)) {
                            // 假设后端返回的数据直接就是用户列表，且每个用户对象包含id和username属性
                            this.userOptions = response.data.map(user => ({
                                id: user.id,
                                userName: user.userName
                            }));
                        } else {
                            this.$message.error('获取用户列表失败，数据格式不正确');
                        }
                    })
                    .catch(error => {
                        this.$message.error('获取用户列表失败：' + error.message);
                    });
            },


        },
   
        //钩子函数，VUE对象初始化完成后自动执行
        created(){
            this.getContractsList();
            this.fetchUsers(); // 在组件创建时加载用户列表
        }
};
</script>
<style>
#search .el-input__inner {
    width: 200px;
    margin-right: 10px;
}
</style>
